package com.fjec.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.BizException;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.common.view.AnnexBizItem;
import com.fjec.market.entity.BizOrderComplaint;
import com.fjec.market.entity.BizSubPhysicalOrder;
import com.fjec.market.feign.BaseClient;
import com.fjec.market.feign.PaidClient;
import com.fjec.market.mapper.BizOrderComplaintMapper;
import com.fjec.market.mapper.BizPhysicalOrderMapper;
import com.fjec.market.service.IBizOrderComplaintService;
import com.fjec.market.service.IBizSubPhysicalOrderService;
import com.fjec.market.service.IInfoSkuService;
import org.elasticsearch.common.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 046.订单投诉表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-21
 */
@Service
public class BizOrderComplaintServiceImpl extends ServiceImpl<BizOrderComplaintMapper, BizOrderComplaint> implements IBizOrderComplaintService {

    @Resource
    private BizOrderComplaintMapper mapper;

    @Resource
    private BaseClient baseClient;

    @Resource
    private IBizSubPhysicalOrderService bizSubPhysicalOrderService;

    @Resource
    private SequenceIdGenerator idGenerator;

    @Autowired
    private PaidClient paidClient;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public JsonResult subOrderComplaint(Long id, String context, String contact, String phone, String picIds, String picUrls) {
        // check子订单是否存在
        BizSubPhysicalOrder subOrder = bizSubPhysicalOrderService.getById(id);
        if (subOrder == null || subOrder.getDelFlag() == 1) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0041.getCode())
                    .message(EnumSysCode.ERR_0041.getMsg())
                    .build();
        }
        // check订单状态是否为已发货
        if (subOrder.getOrderStatus() != 4) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0042.getCode())
                    .message(EnumSysCode.ERR_0042.getMsg())
                    .build();
        }
        Long compId = idGenerator.nextId();
        BizOrderComplaint entity = new BizOrderComplaint();
        entity.setId(compId);
        entity.setUserId(AccountInfo.getUserId());
        entity.setSubOrderId(id);
        entity.setMarkCode(subOrder.getMarkCode());
        entity.setContext(context);
        entity.setContact(contact);
        entity.setPhone(phone);
        entity.setHandleResult(0); // 未处理
        entity.setCreateTime(DateUtil.nowLdt());
        // 保存照片数组
        if (!Strings.isNullOrEmpty(picUrls)) {
            List<String> picUrlList = Arrays.asList(picUrls.split(","));
            entity.setPics(picUrlList);
        }
        mapper.insert(entity);
        // 订单投诉处理
        subOrder.setComplaintStatus(1); // 投诉
        bizSubPhysicalOrderService.updateById(subOrder);

        // 投诉照片有效处理
        if (!Strings.isNullOrEmpty(picIds)) {
            List<AnnexBizItem> itemList = new ArrayList<>();
            List<String> picIdList = Arrays.asList(picIds.split(","));
            picIdList.forEach((String picId) ->{
                AnnexBizItem item = new AnnexBizItem();
                item.setAnnexId(Long.valueOf(picId));
                item.setBizType(5);
                item.setBizId(compId);
                itemList.add(item);
            });
            int ret = baseClient.enableAnnexStatus(itemList);
            if (ret == -1) {
                throw new BizException(EnumSysCode.ERR_3001.getCode(), EnumSysCode.ERR_3001.getMsg());
            }
        }
        return JsonResult.success()
                .code(EnumSysCode.MSG_6002.getCode())
                .message(EnumSysCode.MSG_6002.getMsg())
                .build();
    }

    @Override
    public List<Map<String, Object>> getComplaintsByConditions(Integer searchBy, String title, Integer busiType, Integer markCode, Integer orderType, Integer handleResult, String startTime, String endTime) {
        return mapper.getComplaintsByConditions(searchBy, title, busiType, markCode, orderType, handleResult, startTime, endTime);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int handleComplaint(Long orderId, Long subOrderId, Long complaintId,
                               Integer handleType, String amount, String complaintText) {
        BizSubPhysicalOrder subOrder = bizSubPhysicalOrderService.getOne(new QueryWrapper<BizSubPhysicalOrder>()
                .eq("Id", subOrderId));
        if (subOrder.getComplaintStatus() != 1)
            return -1;

        // 更新子订单投诉状态
        subOrder.setComplaintStatus(2);
        subOrder.setHasRefund(handleType - 1);
        bizSubPhysicalOrderService.updateById(subOrder);

        if (handleType == 2) {
            // 有退款
            int result = paidClient.refund(complaintId, orderId, subOrderId, amount);
            if (result != 0)
                throw new BizException(null, null);
            // 更新投诉表投诉状态 2=退款补偿
            this.update(new UpdateWrapper<BizOrderComplaint>()
                    .eq("SubOrderId", subOrderId)
                    .eq("HandleResult", 0)
                    .set("HandleResult", 2)
                    .set("RefundAmount", (int) (Double.parseDouble(amount) * 100))
                    .set("Advice", complaintText)
                    .set("HandleTime", DateUtil.nowLdt()));
        } else {
            // 无退款 更新投诉表投诉状态 1=不予处理
            this.update(new UpdateWrapper<BizOrderComplaint>()
                    .eq("SubOrderId", subOrderId)
                    .eq("HandleResult", 0)
                    .set("HandleResult", 1)
                    .set("Advice", complaintText)
                    .set("HandleTime", DateUtil.nowLdt()));
        }

        return 0;
    }
}
